<template>
  <div class="ctView">
    <vHeader />
    <vBottomTwo :handleBottomBox="handleBottomBox" @sixView="sixView" @ctView="ctView" :ct="ct"/>
    <vBottom :handleBottomBox="handleBottomBox"/>
    <div ref="ctBox" class="ctBox" :style="{flexDirection:isLandscape?'row':'column'}" v-loading="ct.loading">
      <div class="screen3d" ref="screen3d"></div>
      <div class="screenct" ref="screenct"></div>
      <!-- <div class="screenct" ref="screenct" :style="styleFilter"></div> -->
    </div>
  </div>
</template>

<script>

  import * as THREE from 'three';
  import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';

  import JsZip from "jszip"
  import html2canvas from "html2canvas"

  import {deepCopy} from '@/utils/tools/tools'

  import vHeader from './pub/v-header'
  import vBottom from './ctView/v-bottom'
  import vBottomTwo from './ctView/v-bottom-two'

  import {downloadFile} from '@/depends/api/file'


  let canvas = null
  let ctCanvas = null
  let ctx = null

  let threeObj = {
    renderer: null,
    controls: null,
    scene: null,
    camera: null,
    groupModel: null,
    content: {
      ambientLight: null,
    }
  }

  let touch = {
    start: {
      x: 0,
      y: 0
    },
    move: {
      x: 0,
      y: 0
    },

  }

  export default {
    components: {
      vHeader,
      vBottom,
      vBottomTwo
    },
    data() {
      return {
        isLandscape: true,
        modelPlane: [],
        handleBottomBox: {
          curImg: {
            flag: false
          },
          brightnessFrom: {
            flag: false,
            val: 0
          },
          contrastFrom: {
            flag: false,
            val: 0
          },
          sixView: {
            activeSixViewIndex:0,
            flag: false,
          },
          ctView: {
            flag: false,
            curXYZ: 'Z' // Z, X, Y
          }
        },
        ct: {
          loading: true,
          isPlay: false,

          ctPixelSize: 1,
          ctLayerThickness: 0,

          maxw: 0,
          maxh: 0,

          maxZ: 0,
          indexZ: 1,
          imagesZ: [],

          maxX: 0,
          indexX: 1,
          imagesX: [],

          maxY: 0,
          indexY: 1,
          imagesY: [],

          timer: 0
        }
      };
    },
    props: ['ctLists'],
    computed:{
      styleFilter () {
        return {filter: `contrast(${this.handleBottomBox.contrastFrom.val}%) brightness(${this.handleBottomBox.brightnessFrom.val}%)`}
      },
      bottomTwoShow () {
        let flag = false
        for (let a in this.handleBottomBox) {
          if (this.handleBottomBox[a].flag) { flag = true }
        }
        return flag
      }
    },
    created () {
      this.ct.ctPixelSize = this.ctLists[0].ctPixelSize || 1
      this.ct.ctLayerThickness = this.ctLists[0].ctLayerThickness || 1
      //正式环境显示正常,可能模型的问题,还原回去
      this.ct.maxZ = this.ctLists[0].ctMaxZ || 0
      this.ct.maxX = this.ctLists[0].ctMaxX || 0
      this.ct.maxY = this.ctLists[0].ctMaxY || 0
      //正式环境显示正常,可能模型的问题,本地数据修改为默认1000不然太大的模型肝脏那种显示不出来
      // this.ct.maxZ = this.ctLists[0].ctMaxZ || 1000
      // this.ct.maxX = this.ctLists[0].ctMaxX || 1000
      // this.ct.maxY = this.ctLists[0].ctMaxY || 1000
      console.log(this.ct)

    },
    mounted() {
      // this.initct()
      this.initThree()

      window.addEventListener( 'resize', this.onWindowResize );
      window.addEventListener('keydown', (e) => {
        if (e.keyCode == 37) {
          this.subEvent()
        } else if (e.keyCode == 39) {
          this.addEvent()
        }
      })
      window.addEventListener('mousewheel', (e) => {
        if ((e.wheelDelta || e.detail) < 0) {
          this.addEvent()
        } else {
          this.subEvent()
        }
      });
    },
    methods:{
    //   init () {
    //     this.ct.loading = true
    //     canvas = document.createElement('canvas')
    //     this.$refs.screenct.appendChild(canvas)
    //     ctx = canvas.getContext('2d')
    //     this.onWindowResize(false)
    //     window.addEventListener( 'resize', this.onWindowResize );
    //     downloadFile({fileName: this.ctLists[0].url}).then(res => {
    //       JsZip.loadAsync(res.data).then((zip) => {
    //         Promise.all(Object.values(zip.files).map(a => a.async("base64"))).then((base64s) => {
    //           base64s.forEach((a,b) => {
    //             let image = new Image()
    //             image.src = `data:image/jpg;base64,${a}`
    //             image.onload = () => {
    //               this.ct.images.push(image)
    //               if (b == 0) { this.showImage(this.ct.index) }
    //             }
    //             this.ct.loading = false
    //           })
    //         })
    //       })
    //     })
    // },
      subEvent () {
        if (this.ct[`index${this.handleBottomBox.ctView.curXYZ}`] > 1) {
          this.ct[`index${this.handleBottomBox.ctView.curXYZ}`]--
        }
      },
      addEvent () {
        if (this.ct[`index${this.handleBottomBox.ctView.curXYZ}`] <= this.ct[`images${this.handleBottomBox.ctView.curXYZ}`].length) {
          this.ct[`index${this.handleBottomBox.ctView.curXYZ}`]++
        }
      },
      sixView (type) {
        this.handleBottomBox.sixView.activeSixViewIndex = type;
        let box = new THREE.Box3().setFromObject(threeObj.groupModel)
        const center = box.getCenter( new THREE.Vector3() )
        let boxSize = box.getSize()
        // let max  = parseInt(Math.max(...Object.values(box.size())))
        let n = 2.4
        switch (type) {
          case 1:
            // 前
            threeObj.camera.position.set(center.x, -boxSize.z*n + center.y, center.z )
            break;
          case 2:
            // 后
            threeObj.camera.position.set(center.x, boxSize.z*n + center.y, center.z )
            break;
          case 3:
            // 左
            threeObj.camera.position.set(boxSize.z*n + center.x, center.y, center.z )
            break;
          case 4:
            // 右
            threeObj.camera.position.set(-boxSize.z*n + center.x, center.y, center.z )
            break;
          case 5:
            // 上
            threeObj.camera.position.set(center.x, center.y, boxSize.y*n + center.z )
            break;
          case 6:
            // 下
            threeObj.camera.position.set(center.x, center.y, -boxSize.y*n + center.z )
            break;
        }
        threeObj.controls.update();
      },
      ctView (type) {
        this.handleBottomBox.ctView.curXYZ = type
        this.showImage(this.ct[`index${this.handleBottomBox.ctView.curXYZ}`])
      },
      initThree() {
        const win = this._w_h()

        threeObj.renderer = new THREE.WebGLRenderer({ preserveDrawingBuffer: true, antialias: true })
        // threeObj.renderer.setPixelRatio(window.devicePixelRatio);
        // dpr > 2 的机型如：iphone6plus 等，需注意模型太大时，会导致闪退，需要设置
        threeObj.renderer.setPixelRatio(window.devicePixelRatio<3 ? window.devicePixelRatio : 1)
        threeObj.renderer.setSize(win.w, win.h);
        //根据系统输入的XYZ裁剪平面,输入值不同进来看到的不同
        //这个裁剪导致的有的才进来显示不出来,XYZ填大点就出来了
        this.modelPlane = [
        new THREE.Plane( new THREE.Vector3( - 1, 0, 0 ), 0 ),
          new THREE.Plane( new THREE.Vector3( 0, - 1, 0 ), 0 ),
          new THREE.Plane( new THREE.Vector3( 0, 0, - 1 ), 0 )         
        ];

        threeObj.renderer.clippingPlanes = this.modelPlane
        // threeObj.renderer.localClippingEnabled = true;

        this.$refs.screen3d.appendChild(threeObj.renderer.domElement);

        threeObj.scene = new THREE.Scene();
         threeObj.scene.background = new THREE.Color(0x000000);
        //threeObj.scene.background = new THREE.Color(0xffffff);
        threeObj.scene.add( new THREE.AmbientLight( 0xffffff, 0.2 ) );

      threeObj.camera = new THREE.PerspectiveCamera(45, win.w/win.h, 50, 10000);
      threeObj.camera.add( new THREE.PointLight( 0xffffff, 0.8 ) );
      threeObj.camera.up.set( 0, 0, 1 );
      threeObj.scene.add( threeObj.camera );

      
        //执行渲染操作   指定场景、相机作为参数
        // threeObj.renderer.render(threeObj.scene, threeObj.camera);
        threeObj.controls = new OrbitControls(threeObj.camera, threeObj.renderer.domElement);
        threeObj.controls.target.set( 0, 0, 0 );
        threeObj.controls.update();
        threeObj.controls.addEventListener( 'change', this.render );

      },
      resetXYZ () {
        // threeObj.renderer.constant = parseInt(20)
        let box = new THREE.Box3().setFromObject(threeObj.groupModel)

        // this.modelPlane[0].constant = 80

        const center = box.getCenter( new THREE.Vector3() )
        threeObj.controls.target.x += ( threeObj.controls.target.x + center.x );
        threeObj.controls.target.y += ( threeObj.controls.target.y + center.y );
        threeObj.controls.target.z += ( threeObj.controls.target.z + center.z );

        // console.log(new THREE.Box3().setFromObject(threeObj.groupModel),threeObj.controls.target)

        let boxSize = box.getSize()

        threeObj.camera.position.set(threeObj.controls.target.x, -boxSize.z*2.4 + threeObj.controls.target.y, threeObj.controls.target.z )

        threeObj.camera.updateProjectionMatrix();
        threeObj.controls.update();
        this.render();
      },
      render() {
        console.log(threeObj.scene)
        console.log(threeObj.groupModel)
        threeObj.renderer.render( threeObj.scene, threeObj.camera );

      },
      touchstart (e) {
        if (e.touches) {
          if (e.touches.length>1) { return }
          e.clientX = e.touches[0].clientX
          e.clientY = e.touches[0].clientY
        }
        touch.start.x = e.clientX
        touch.start.y = e.clientY
      },
      touchmove (e) {
        if (touch.start.x === 0 && touch.start.y === 0) { return }
        if (e.touches) {
          if (e.touches.length>1) { return }
          e.clientX = e.touches[0].clientX
          e.clientY = e.touches[0].clientY
        }
        touch.move.x = e.clientX
        touch.move.y = e.clientY

        this.showImage(this.ct[`index${this.handleBottomBox.ctView.curXYZ}`])
      },
      touchend (e) {
        if (touch.start.x === 0 && touch.start.y === 0) { return }
        if (touch.move.x === 0 && touch.move.y === 0) { return }
        const touchREXT = 4
        const movex = parseInt((touch.move.x - touch.start.x) / touchREXT)
        const movey = parseInt(- (touch.move.y - touch.start.y) / touchREXT)
        let [a, b] = [this.handleBottomBox.brightnessFrom.val, this.handleBottomBox.contrastFrom.val]

        if (a + movex > 100) { a = 100 } else if (a + movex < -100) { a = -100 } else { a = a + movex }
        if (b + movey > 200) { b = 200 } else if (b + movey < -200) { b = -200 } else { b = b + movey }
        this.handleBottomBox.brightnessFrom.val = a
        this.handleBottomBox.contrastFrom.val = b
        this.showImage(this.ct[`index${this.handleBottomBox.ctView.curXYZ}`])

        touch = {
          start: {
            x: 0,
            y: 0
          },
          move: {
            x: 0,
            y: 0
          },
        }
      },
      initct () {
        downloadFile({fileName: this.ctLists[0].url}).then(res => {
          JsZip.loadAsync(res.data).then((zip) => {
            Promise.all(Object.values(zip.files).map(a => a.async("base64"))).then((base64s) => {
              // base64s.forEach((a,b) => {
              //   let image = new Image()
              //   image.src = `data:image/jpg;base64,${a}`
              //   this.ct.imagesZ.push(image)
              //   this.ct.loading = false
              // })
              // if (this._w_h().w) { this.showImage(this.ct.indexZ) }

              this.creatImagesData(base64s)
            })
          })
        })

        ctCanvas = document.createElement('canvas')
        ctCanvas.style.backgroundColor = '#000'
        // const win = this._w_h()
        // ctCanvas.width = win.w
        // ctCanvas.height = win.h
        this.$refs.screenct.appendChild(ctCanvas)

        ctCanvas.addEventListener('touchstart', this.touchstart, false)
        ctCanvas.addEventListener('touchmove', this.touchmove, false)
        ctCanvas.addEventListener('touchend', this.touchend, false)


        ctCanvas.addEventListener('mousedown', this.touchstart, false)
        ctCanvas.addEventListener('mousemove', this.touchmove, false)
        ctCanvas.addEventListener('mouseup', this.touchend, false)

        ctx = ctCanvas.getContext('2d')



      },
      creatImagesData (base64s) {
        let _cvs = document.createElement('canvas')
        _cvs.id = '_cvs'
        // document.body.appendChild(_cvs)
        let _ctx = _cvs.getContext('2d')

        let xz = [], yz = []
        let w, h
        let th = base64s.length
        Promise.all(base64s.map(a => { return this.imageLoadPromise(_cvs, _ctx, `data:image/jpg;base64,${a}`) })).then((imageDatas) => {
          w = imageDatas[0].width
          h = imageDatas[0].height
          imageDatas.forEach((imgdata, z) => {
            for (let y = 0; y < h; y++) {
              for (let x = 0; x < w; x++) {
                if (!xz[h-y-1]) { xz[h-y-1] = new Uint8ClampedArray(w * imageDatas.length * 4) }
                if (!yz[w-x-1]) { yz[w-x-1] = new Uint8ClampedArray(h * imageDatas.length * 4) }

                xz[h-y-1][(x + (imageDatas.length - z) * w) * 4] = imgdata.data[(x + w * y) * 4]
                xz[h-y-1][(x + (imageDatas.length - z) * w) * 4 + 1] = imgdata.data[(x + w * y) * 4 + 1]
                xz[h-y-1][(x + (imageDatas.length - z) * w) * 4 + 2] = imgdata.data[(x + w * y) * 4 + 2]
                xz[h-y-1][(x + (imageDatas.length - z) * w) * 4 + 3] = imgdata.data[(x + w * y) * 4 + 3]

                yz[w-x-1][((h - y) + (imageDatas.length-z) * h) * 4] = imgdata.data[(x + w * y) * 4]
                yz[w-x-1][((h - y) + (imageDatas.length-z) * h) * 4 + 1] = imgdata.data[(x + w * y) * 4 + 1]
                yz[w-x-1][((h - y) + (imageDatas.length-z) * h) * 4 + 2] = imgdata.data[(x + w * y) * 4 + 2]
                yz[w-x-1][((h - y) + (imageDatas.length-z) * h) * 4 + 3] = imgdata.data[(x + w * y) * 4 + 3]
              }
            }
          })

          this.ct.imagesZ = imageDatas
          this.ct.imagesY = xz.map(a => new ImageData(a, w, th))
          this.ct.imagesX = yz.map(a => new ImageData(a, h, th))
          this.ct.imagesZ.reverse()

          let realitySize = [this.ct.imagesZ[0].width * this.ct.ctPixelSize, this.ct.imagesZ[0].height * this.ct.ctPixelSize,
            this.ct.imagesY[0].width * this.ct.ctPixelSize, this.ct.imagesY[0].height * this.ct.ctLayerThickness,
            this.ct.imagesX[0].width * this.ct.ctPixelSize, this.ct.imagesX[0].height * this.ct.ctLayerThickness]
          this.ct.maxw = Math.max(...[realitySize[0], realitySize[2], realitySize[4]])
          this.ct.maxh = Math.max(...[realitySize[1], realitySize[3], realitySize[5]])


          this.ct.loading = false
          this.onWindowResize()
          // if (this._w_h().w) { this.showImage(this.ct[`index${this.handleBottomBox.ctView.curXYZ}`]) }

          // maxZ: 0,
          // indexZ: 1,
          // imagesZ: [],
          // ctLayerThickness: 0,

          // maxX: 0,
          // indexX: 1,
          // imagesX: [],
          // ctPixelSize: 0,

          // maxY: 0,
          // indexY: 1,
          // imagesY: [],

          // _ctx.clearRect(0, 0, w, h)
          // _ctx.putImageData(this.ct.imagesY[5], 0, 0);
          // _ctx.putImageData(this.ct.imagesY[100], 0, 200);
        })
      },
      imageLoadPromise (_cvs, _ctx, base64) {
        return new Promise((resolve) => {
          let image = new Image()
          image.src = base64
          image.onload = () => {
            _cvs.width = image.width
            _cvs.height = image.height
            _ctx.drawImage(image, 0, 0, image.width, image.height)
            // console.log(111, _ctx.getImageData(0,0,image.width,image.height))
            resolve(_ctx.getImageData(0,0,image.width,image.height))
          }
        })
      },
      // showOne() {
      //   if (!this.ct.imagesZ.length && this.ct.loading) {
      //     this.initct()
      //   }
      //   this.$nextTick(() => {
      //     this.onWindowResize()
      //   })
      // },
      showImage (i) {
        this.setBrightnessContrastFrom(this.handleBottomBox.brightnessFrom.val, this.handleBottomBox.contrastFrom.val)
        if (threeObj.groupModel) {
          let _thickness = this.handleBottomBox.ctView.curXYZ == 'Z' ? this.ct.ctLayerThickness : this.ct.ctPixelSize

          let curLength = this.ct[`max${this.handleBottomBox.ctView.curXYZ}`] - _thickness * (i-1)
          const xyzMap = ['X', 'Y', 'Z']
          // console.log(this.handleBottomBox.ctView.curXYZ, '111111111111111111', curLength, this.ct[`max${this.handleBottomBox.ctView.curXYZ}`], this.ct[`thickness${this.handleBottomBox.ctView.curXYZ}`] * (i-1))
           this.modelPlane[xyzMap.indexOf(this.handleBottomBox.ctView.curXYZ)].constant = curLength
          this.render();
        }
      },
      goPlay () {
        this.ct.isPlay = !this.ct.isPlay
        const xyzMap = ['X', 'Y', 'Z']
        if (this.ct.isPlay) {
          if (this.ct[`index${this.handleBottomBox.ctView.curXYZ}`] == this.ct[`images${this.handleBottomBox.ctView.curXYZ}`].length) { this.ct[`index${this.handleBottomBox.ctView.curXYZ}`] = 1}
          this.palyer()
        } else {
          clearTimeout(this.ct.timer)
        }
      },
      palyer () {
        if (this.ct[`index${this.handleBottomBox.ctView.curXYZ}`] == this.ct[`images${this.handleBottomBox.ctView.curXYZ}`].length) { this.ct.isPlay = false;clearTimeout(this.ct.timer);return }
        this.ct.timer = setTimeout(() => {
          this.ct[`index${this.handleBottomBox.ctView.curXYZ}`]++
          this.showImage(this.ct[`index${this.handleBottomBox.ctView.curXYZ}`])
          this.palyer()
        }, 100)
      },
      setIndex (a) {
        this.ct[`index${this.handleBottomBox.ctView.curXYZ}`] = a
        if (this.ct.imagesZ.length) this.showImage(this.ct[`index${this.handleBottomBox.ctView.curXYZ}`])

      },
      onBlur () {
        window.scrollTo(0, 0)
      },
      setBrightness (a) {
        // 亮度
        // if (!ctImageData) { return }
        this.setBrightnessContrastFrom(this.handleBottomBox.brightnessFrom.val, this.handleBottomBox.contrastFrom.val)
        // return
        // const longStep = 2.55 * a
        // let newImageData = ctx.getImageData(0, 0, ctCanvas.width, ctCanvas.height)
        // for (let i = 0; i < newImageData.data.length - 4; i += 4) {
        //   newImageData.data[i] = ctImageData[i] + longStep > 255 ? 255 : ctImageData[i] + longStep
        //   newImageData.data[i + 1] = ctImageData[i + 1] + longStep > 255 ? 255 : ctImageData[i + 1] + longStep
        //   newImageData.data[i + 2] = ctImageData[i + 2] + longStep > 255 ? 255 : ctImageData[i + 2] + longStep
        //   newImageData.data[i + 3] = 255
        // }
        // ctx.putImageData(newImageData, 0, 0);
      },
      setContrastFrom (a) {
        // 对比度
        // if (!ctImageData) { return }
        this.setBrightnessContrastFrom(this.handleBottomBox.brightnessFrom.val, this.handleBottomBox.contrastFrom.val)
        // return
        // const longStep = 50
        // let newImageData = ctx.getImageData(0, 0, ctCanvas.width, ctCanvas.height)
        // for (let i = 0; i < newImageData.data.length - 4; i += 4) {
        //   newImageData.data[i] = ctImageData[i] + (ctImageData[i] - longStep) * (1 / (1 - a / 255) - 1)
        //   newImageData.data[i + 1] = ctImageData[i + 1] + (ctImageData[i + 1] - longStep) * (1 / (1 - a / 255) - 1)
        //   newImageData.data[i + 2] = ctImageData[i + 2] + (ctImageData[i + 2] - longStep) * (1 / (1 - a / 255) - 1)
        //   newImageData.data[i + 3] = 255
        // }
        // ctx.putImageData(newImageData, 0, 0);

// 1、计算平均亮度

// 2、每点与平均亮度比较，得到差值。

// 3、新的亮度 = 平均亮度 + 系数 * 差值

// 4、根据新的亮度，计算出新的rgb(保持色调不变)

      },
      setBrightnessContrastFrom(a, b) {

        // _ctx.putImageData(this.ct.imagesY[5], 0, 0);
        // _ctx.putImageData(this.ct.imagesY[100], 0, 200);
        if (!this.ct[`images${this.handleBottomBox.ctView.curXYZ}`].length) { return }
        let ctImageData = this.ct[`images${this.handleBottomBox.ctView.curXYZ}`][this.ct[`index${this.handleBottomBox.ctView.curXYZ}`] - 1]
        const touchREXT = 4
        const movex = parseInt((touch.move.x - touch.start.x) / touchREXT)
        const movey = parseInt(- (touch.move.y - touch.start.y) / touchREXT)

        if (a + movex > 100) { a = 100 } else if (a + movex < -100) { a = -100 } else { a = a + movex }
        if (b + movey > 200) { b = 200 } else if (b + movey < -200) { b = -200 } else { b = b + movey }

        const longStep = 2.55 * a
        const factor = 20
        if (!ctCanvas.width) { return }
        let newImageData = new Uint8ClampedArray(ctImageData.data.length)
        for (let i = 0; i < newImageData.length - 4; i += 4) {

          newImageData[i] = ctImageData.data[i] + longStep > 255 ? 255 : ctImageData.data[i] + longStep
          newImageData[i + 1] = ctImageData.data[i + 1] + longStep > 255 ? 255 : ctImageData.data[i + 1] + longStep
          newImageData[i + 2] = ctImageData.data[i + 2] + longStep > 255 ? 255 : ctImageData.data[i + 2] + longStep


          newImageData[i] = newImageData[i] + (newImageData[i] - factor) * (1 / (1 - b / 255) - 1)
          newImageData[i + 1] = newImageData[i + 1] + (newImageData[i + 1] - factor) * (1 / (1 - b / 255) - 1)
          newImageData[i + 2] = newImageData[i + 2] + (newImageData[i + 2] - factor) * (1 / (1 - b / 255) - 1)


          newImageData[i + 3] = 255
        }
        let curimage = new ImageData(newImageData, ctImageData.width, ctImageData.height)
        this.imagedataToImgObj(curimage, (imgObj) => {

          const win = this._w_h()

          // ctx.clearRect(0, 0, win.w, win.h)
          // console.log(curimage.width, curimage.height)
          // ctx.drawImage(imgObj, 0, 0, curimage.width, curimage.height, 0, 0, curimage.width, curimage.height)
          // return

          let w, h, ratio
// this.ct.maxw
// this.ct.maxh

          if (['X', 'Y'].includes(this.handleBottomBox.ctView.curXYZ)) {
            w = curimage.width * this.ct.ctPixelSize
            h = curimage.height * this.ct.ctLayerThickness
          } else {
            w = curimage.width * this.ct.ctPixelSize
            h = curimage.height * this.ct.ctPixelSize
          }
          // if (win.w / this.ct.maxw > win.h / this.ct.maxh) {
          //   ratio = win.h / this.ct.maxh
          // } else {
          //   ratio = win.w / this.ct.maxw
          // }
          ratio = win.w / this.ct.maxw > win.h / this.ct.maxh ? win.h / this.ct.maxh : win.w / this.ct.maxw
          w = w * ratio
          h = h * ratio
          // console.log(this.handleBottomBox.ctView.curXYZ, w, h)


          ctx.clearRect(0, 0, win.w, win.h)
          ctx.drawImage(imgObj, 0, 0, curimage.width, curimage.height, (win.w-w)/2, (win.h-h)/2, w, h)
        })
      },
      imagedataToImgObj (imagedata, callBack) {
        let _cvs = document.createElement('canvas')
        _cvs.id = '_cvs'
        _cvs.width = imagedata.width
        _cvs.height = imagedata.height
        let _ctx = _cvs.getContext('2d')
        _ctx.putImageData(imagedata, 0, 0)
        let _img = new Image()
        _img.src = _cvs.toDataURL('image/jpeg')
        _img.onload = () => {
          callBack(_img)
        }
      },
      clipPic () {
        // this.$emit('upDate', 'ctScreenshot', 255, this.$refs.screenct.querySelector('canvas').toDataURL())

        return new Promise((resolve, reject) => {

          // let labelBoxAll = document.querySelectorAll('.labelBox')
          // let transforms = []
          // labelBoxAll.forEach((a, b) => {
          //   transforms.push(a.style.transform)
          //    const _tf = a.style.transform.match(/(\d*\.?\d*)/g).filter(x => x)
          //    a.style.transform = ''
          //    a.style.top = `${-a.offsetHeight/2 + Number(_tf[3])}px`
          //    a.style.left = `${-a.offsetWidth/2 + Number(_tf[2])}px`
          // })
          html2canvas(this.$refs.ctBox, {scale: window.devicePixelRatio}).then(canvas => {
            let dataURL = canvas.toDataURL("image/png");
            // console.log(dataURL, 111)
            resolve(dataURL)
          });

        })
      },


      busModel (a) {
        threeObj.groupModel = a
        threeObj.scene.add( threeObj.groupModel )
        this.resetXYZ()

        // const xyzMap = ['X', 'Y', 'Z']
        // this.modelPlane[xyzMap.indexOf(this.handleBottomBox.ctView.curXYZ)].constant = curLength

        this.modelPlane[0].constant = this.ct.maxX
        this.modelPlane[1].constant = this.ct.maxY
        this.modelPlane[2].constant = this.ct.maxZ
        this.render();
      },
      _w_h () {
        let _w = this.$refs.ctBox.offsetWidth, _h = this.$refs.ctBox.offsetHeight
        let _w2 = 0, _h2 = 0
        if (_w >= _h) {
          // 横
          this.isLandscape = true
          _w2 = _w/2
          _h2 = _h
        } else {
          // 竖
          this.isLandscape = false
          _w2 = _w
          _h2 = _h/2
        }
        return {w: _w2, h: _h2}
      },
      onWindowResize () {
        this.$nextTick(() => {
          const win = this._w_h()
          ctCanvas.width = win.w
          ctCanvas.height = win.h
          this.showImage(this.ct[`index${this.handleBottomBox.ctView.curXYZ}`])



          threeObj.camera.aspect = win.w/win.h;
          threeObj.camera.updateProjectionMatrix();
          threeObj.renderer.setSize( win.w, win.h );
          this.render();

        })
      },
    },
    beforeDestroy() {
      //内存中销毁删除
      try {
          threeObj.scene.clear()
          threeObj.renderer.dispose()
      } catch (e) {
          console.log(e)
      }
    },
  }
</script>
<style scoped lang="less">
  .ctView {
    height: calc(100% - 30px);
    // height: 100%;
    padding-top: 30px;
    overflow: hidden;
    background-color: #000;
    .v-header .header .infoBox .feature {
      color: #fff;
    }
    .ctBox {
      height: 100%;
      // height: calc(100% - 50px);
      display: flex;
      .screen3d,.screenct {
        flex: 1;
        overflow: hidden;
      }
    }
  }
</style>

<style lang="less">
  #_cvs {
    position: fixed;
    left: 0;
    top: 50px;
    z-index: 10;
    width: 300PX;
  }
</style>
